package com.linghui.videoplus.ipai.utils;


import com.linghui.videoplus.ipai.VideoPlusApplication;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaMetadataRetriever;

public class ImageUtils {

	public static Bitmap getVideoImage(String imageFilePath, final int width,
			final int height) {
		Bitmap bitmap = null;
		try {
			if (VideoPlusApplication.getAndroidSDKVersion() > 7) {
				bitmap = android.media.ThumbnailUtils
						.createVideoThumbnail(
								imageFilePath,
								android.provider.MediaStore.Images.Thumbnails.MINI_KIND);
				bitmap = android.media.ThumbnailUtils.extractThumbnail(bitmap,
						width, height,
						android.media.ThumbnailUtils.OPTIONS_RECYCLE_INPUT);
			} else {
				bitmap = getLocalBitmap(imageFilePath, width, height);
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
		return bitmap;
	}

	/**
	 * 获得本地照片
	 * 
	 * @param imageFilePath
	 * @param DISPLAYHEIGHT
	 * @param DISPLAYWIDTH
	 * @return
	 */
	public static Bitmap getLocalBitmap(String imageFilePath,
			final int width, final int height) {
		BitmapFactory.Options bmpFactoryOptions = new BitmapFactory.Options();
		bmpFactoryOptions.inJustDecodeBounds = true;
		Bitmap bmp = BitmapFactory.decodeFile(imageFilePath, bmpFactoryOptions);
		
		int widthRatio = (int) Math.ceil(bmpFactoryOptions.outWidth
				/ (float) width);
		
		int heightRatio = (int) Math.ceil(bmpFactoryOptions.outHeight
				/ (float) height);
		
		if (heightRatio > 1 && widthRatio > 1) {
			if (heightRatio > widthRatio) {
				bmpFactoryOptions.inSampleSize = heightRatio;
			} else {
				bmpFactoryOptions.inSampleSize = widthRatio;
			}
		}
		bmpFactoryOptions.inJustDecodeBounds = false;
		bmp = BitmapFactory.decodeFile(imageFilePath, bmpFactoryOptions);
		return bmp;
	}

	public static Bitmap createVideoThumbnail(String filePath) {
		Bitmap bitmap = null;
		MediaMetadataRetriever retriever = new MediaMetadataRetriever();
		try {
			retriever.setMode(MediaMetadataRetriever.MODE_CAPTURE_FRAME_ONLY);
			retriever.setDataSource(filePath);
			bitmap = retriever.captureFrame();
		} catch (IllegalArgumentException ex) {
		} catch (RuntimeException ex) {
		} finally {
			try {
				retriever.release();
			} catch (RuntimeException ex) {
				// Ignore failures while cleaning up.
			}
		}
		return bitmap;
	}
}
